package com.xj.community.Service;

import com.xj.community.dao.LoginTicketMapper;
import com.xj.community.dao.UserMapper;
import com.xj.community.entity.LoginTicket;
import com.xj.community.entity.User;
import com.xj.community.util.CommunityConstant;
import com.xj.community.util.CommunityUtil;
import com.xj.community.util.MailClient;
import com.xj.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class UserService implements CommunityConstant {
    @Autowired
    private LoginTicketMapper loginTicketMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private MailClient mailClient;


    public User selectById(int id){
//        User user = userMapper.selectById(id);
        User user = cacheFind(id);
        if (user == null){
            user = mysqlFind(id);
        }
        return user;
    }

    /**
     * 注册用户
     * Map集合用于存储返回操作结果页面时所需要的参数
     */
    public Map<String,Object> register(User user){
        HashMap<String, Object> map = new HashMap<>();

        //null值处理
        if(user == null){
            throw new IllegalArgumentException("参数不能为空！");
        }
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg","用户名不能为空！");
            return map;
        }
        if(StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg","邮箱不能为空!");
            return map;
        }
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg","密码不能为空！");
            return map;
        }

        //验证账号,要求用户名不能重复
        User u = userMapper.selectByName(user.getUsername());
        if(u != null){
            map.put("usernameMsg","该账号已经注册！");
            return map;
        }

        //验证邮箱
        u = userMapper.selectByEmail(user.getEmail());
        if(u != null){
            map.put("emailMsg","该邮箱已经注册!");
            return map;
        }


        // 注册用户
        //生成一个随机字符串用于和用户的密码进行拼接
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);//默认为普通用户
        user.setStatus(0);//默认未激活
        user.setActivationCode(CommunityUtil.generateUUID());//生成一个随机激活码
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        //发送激活邮件
        Context context = new Context();
        // 设置模板中的变量
        context.setVariable("email", user.getEmail());
        //生成激活链接,http://localhost:8080/community/activation/101/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url",url);
        //通过模板引擎格式化邮件
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendHtml(user.getEmail(),"激活账号",content);

        return map;
    }

    public int activate(int userId,String code){
        User user = userMapper.selectById(userId);
        if(user.getStatus() == 1 ){
            return ACTIVATION_REPEAT;
        }else if(user.getActivationCode().equals(code)){
            userMapper.updateStatus(userId,1);
            clearCache(userId);
            return ACTIVATION_SUCCESS;
        }else{
            return ACTIVATION_FAILURE;
        }
    }

    /**
     * 登录
     * @param username
     * @param password
     * @param expireSeconds:过期时间
     * @return
     */
    public Map<String,Object> login(String username,String password,int expireSeconds){
        Map<String,Object> map = new HashMap<>();
        //空值判断
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg","账号不能为空");
            return map;
        }
        if(StringUtils.isBlank(password)){
            map.put("passwordMsg","密码不能为空");
        }

        User user = userMapper.selectByName(username);
        //验证账号是否已经存在
        if( user== null){
            map.put("usernameMsg","该账号还未注册");
            return map;
        }

        //验证状态
        if(user.getStatus() == 0){
            map.put("usernameMsg","该账号还未激活");
            return map;
        }

        //验证密码
        //数据库存储的密码是如何生成的：随机字符串和密码拼接->MD5算法加密
        if(!(CommunityUtil.md5(password+user.getSalt())).equals(user.getPassword())){
            map.put("passwordMsg","密码不正确");
            return map;
        }

        //将凭证存储到数据库中
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setStatus(0);
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setExpired(new Date(System.currentTimeMillis()+expireSeconds*1000));//注意单位换算
//        loginTicketMapper.insertLoginTicket(loginTicket);

        String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(redisKey,loginTicket);

        map.put("ticketMsg",loginTicket.getTicket());
        return map;


    }

    /**
     * 退出登录
     */
    public void logOut(String ticket){
//        loginTicketMapper.updateLoginTicket(ticket,1);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(redisKey,loginTicket);
    }

    /**
     * 查找凭证
     * @param ticket
     * @return
     */
    public LoginTicket findLoginTicket(String ticket) {
//        LoginTicket loginTicket = loginTicketMapper.selectByTicket(ticket);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        return loginTicket;
    }

    //更新当前用户的头像路径
    public void updateHead(int userId,String headerUrl){
        userMapper.updateHeader(userId,headerUrl);
        clearCache(userId);
    }

    //更新密码
    public void updatePwd(int id, String md5) {
        userMapper.updatePassword(id,md5);
        clearCache(id);
    }

    public User findUserByName(String toName) {
        return userMapper.selectByName(toName);
    }

    //1.首先到redis缓存中查询用户信息
    public User cacheFind(int userId){
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    //2.如果缓存中没有则到mysql中查询并初始化缓存
    public User mysqlFind(int userId){
        String redisKey = RedisKeyUtil.getUserKey(userId);
        User user = userMapper.selectById(userId);
        redisTemplate.opsForValue().set(redisKey,user);
        return user;
    }

    //3.更新用户信息时直接清除缓存
    public void clearCache(int userId){
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }
}
